import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sun.xml.internal.bind.v2.model.core.ID;
import kit.Kit;

/**
 * Created by Administrator on 2017/10/19.
 */
public class BuildJSON {
    private volatile static int Id = 0;
    public static void main (String [] args) throws Exception{
        int id = 1;
        JSONObject json = getJson("");
        StringBuilder res = new StringBuilder("insert into one_china_city(id,name,level,parent_id)values\r\n");
        int pid = add(res,getName(json),1,-1);
        addArray(res,json,2,pid);

        System.out.println(res);
    }

    public static String getName(JSONObject json){
        return json.getString("name");
    }
    public static void addArray(StringBuilder sql,JSONObject json,int level,int parentId){
        JSONArray array = json.getJSONArray("list");
        if(array.size() > 0){
            for(int i = 0 ; i < array.size() ; i ++){
                JSONObject data = array.getJSONObject(i);
                int pid = add(sql,getName(data),level,parentId);

                addArray(sql, data, level + 1, pid);
            }
        }
    }

    public static int add(StringBuilder sql,String name,int level,int parentId){
        if(level > 3){return -1;}
        int id = getId();
        sql.append("("+id+",'"+name+"',"+level+","+parentId+"),\r\n");
        return id;
    }

    public static int getId(){
        Id ++ ;
        return Id;
    }

    private static JSONObject getJson(String path) throws Exception{
        String str = Kit.getFile("E:/citys/河北省-1.json","gb2312");
        System.out.println(str);
        return (JSONObject)JSON.parse(str);
    }
}
